package com.hgm.travelapp.fragment

import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.*
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.bumptech.glide.Glide
import com.hgm.travelapp.R
import com.hgm.travelapp.activity.DetailsActivity
import com.hgm.travelapp.activity.SearchActivity
import com.hgm.travelapp.adapter.RecyclerViewAdapter
import com.hgm.travelapp.bean.Banner
import com.hgm.travelapp.bean.HomeList
import com.hgm.travelapp.databinding.FragmentHomeBinding
import com.hgm.travelapp.network.ApiService
import com.hgm.travelapp.network.RetrofitClient
import com.youth.banner.adapter.BannerImageAdapter
import com.youth.banner.holder.BannerImageHolder
import com.youth.banner.indicator.CircleIndicator
import retrofit2.Call
import retrofit2.Response

class HomeFragment : Fragment() {

    private val mBinding: FragmentHomeBinding by lazy {
        FragmentHomeBinding.inflate(layoutInflater)
    }


    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        return mBinding.root
    }

    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        initData()
        initEvent()
    }

    private fun initEvent() {
        mBinding.searchView.setOnClickListener {
            startActivity(Intent(this.context, SearchActivity::class.java))
        }
        mBinding.toTop.setOnClickListener {
            mBinding.recyclerView.scrollToPosition(0)
        }
    }

    private fun initData() {
        //加载轮播图
        loadBannerData()
        //加载列表
        loadRecyclerView()
    }


    /**
     * 加载票子列表
     */
    private fun loadRecyclerView() {

        RetrofitClient.create(ApiService::class.java).getHomeList().enqueue(object : retrofit2.Callback<HomeList>{
            override fun onResponse(call: Call<HomeList>, response: Response<HomeList>) {
                Log.e("hgm", "首页列表请求成功: ${response.body().toString()}")
                //获取列表数据
                val homeList = response.body()?.data
                //初始化recyclerview
                var recyclerAdapter = RecyclerViewAdapter(homeList)
                mBinding.recyclerView.apply {
                    layoutManager = StaggeredGridLayoutManager(2, StaggeredGridLayoutManager.VERTICAL)
                    adapter = recyclerAdapter
                }

                //recyclerview的item点击事件
                recyclerAdapter.setOnItemClickListener(object : RecyclerViewAdapter.OnItemClickListener {
                    override fun onItemClick(pos: Int) {
                        startActivity(Intent(activity, DetailsActivity::class.java))
                    }
                })
            }

            override fun onFailure(call: Call<HomeList>, t: Throwable) {
                Log.e("hgm", "首页列表请求失败: ${t.message}")
            }
        })


        //监听recyclerview滑动到底部
        mBinding.recyclerView.setOnScrollChangeListener { v, scrollX, scrollY, oldScrollX, oldScrollY ->
            val i = mBinding.recyclerView.computeVerticalScrollOffset()
            if (i > 3000) {
                mBinding.toTop.visibility = View.VISIBLE
            } else {
                mBinding.toTop.visibility = View.GONE
            }
        }
    }


    /**
     * 加载轮播图
     */
    private fun loadBannerData() {
        val dataList =
            listOf(R.drawable.banner, R.drawable.banner2, R.drawable.banner, R.drawable.banner2)

        RetrofitClient.create(ApiService::class.java)
            .getBanner().enqueue(object : retrofit2.Callback<Banner> {
                override fun onResponse(call: Call<Banner>, response: Response<Banner>) {
                    Log.e("hgm", "轮播图请求成功:${response.body().toString() ?: "response is null"} ")
                    // 【缺少数据，改为本地加载图片】
                    // //获取集合
                    // val dataList = response.body()?.data
                    // // banner自带图片轮播的适配器
                    // mBinding.banner.setAdapter(object :
                    //     BannerImageAdapter<BannerData?>(dataList) {
                    //     override fun onBindView(
                    //         holder: BannerImageHolder?,
                    //         data: BannerData?,
                    //         position: Int,
                    //         size: Int
                    //     ) {
                    //         Glide.with(this@MainActivity)
                    //             .load(data!!.imgUrl)
                    //             .into(holder!!.imageView)
                    //     }
                    // }).addBannerLifecycleObserver(this@MainActivity) //添加生命周期观察者
                    //     .setIntercept(false).indicator =
                    //     CircleIndicator(this@MainActivity) //圆形指示器 还支持条形指示器等
                    mBinding.banner.setAdapter(object : BannerImageAdapter<Int>(dataList) {
                        override fun onBindView(
                            holder: BannerImageHolder?,
                            data: Int?,
                            position: Int,
                            size: Int
                        ) {
                            Glide.with(this@HomeFragment.context)
                                .load(data)
                                .into(holder!!.imageView)
                        }
                    }).addBannerLifecycleObserver(this@HomeFragment) //添加生命周期观察者
                        .setIntercept(false).indicator =
                        CircleIndicator(this@HomeFragment.context) //圆形指示器 还支持条形指示器等
                }

                override fun onFailure(call: Call<Banner>, t: Throwable) {
                    Log.e("hgm", "轮播图请求失败:${t.printStackTrace()} ")
                }
            })
    }
}